package com.ruoyi.crm.service.impl;

import com.ruoyi.crm.domain.Contract;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;

@Service
public class CrmMailService {
    public static final String TEMPLATE_CONTRACT_CREATED="contractCreated.html";
    @Resource
    private JavaMailSender javaMailSender;
    @Resource
    private TemplateEngine templateEngine;
    @Value("${spring.mail.username}")
    private String username;

    @SneakyThrows
    public void sendContractCreatedMail(Contract contract){
        Context context=new Context();
        context.setVariable("username",contract.getName());// 用户名
        context.setVariable("contractNo",contract.getContractNo()); // 合同编号
        context.setVariable("contractOrder",contract.getContractOrder()); // 价值
        String mailText=templateEngine.process(TEMPLATE_CONTRACT_CREATED,context);
        // 发送邮件
        MimeMessage mimeMessage=javaMailSender.createMimeMessage();
        MimeMessageHelper helper=new MimeMessageHelper(mimeMessage);
        helper.setSubject("感谢您成功订购：【"+contract.getCourseName()+"】");
        helper.setFrom(username);// 发件人
        helper.setTo(contract.getEmail());
        helper.setText(mailText,true); // 用网页的方式发送
        javaMailSender.send(mimeMessage);
    }


}
